package service.impl;

import dao.IUserDao;
import domain.Role;
import domain.Users;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import service.IUserService;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Freedy
 * @date 2020/12/25 17:08
 */
@Service("userService")
@Transactional
public class UserServiceImpl implements IUserService {
    @Autowired
    private IUserDao userDao;
    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Users user=null;
        try {
            user = userDao.findByUserName(username);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (user != null) {
            return new User(user.getUsername(),user.getPassword(),
                    user.getStatus() != 0,true,true,true,
                    getAuthority(user.getRoles()));
        }else {
            return null;
        }
    }

    private List<SimpleGrantedAuthority> getAuthority(@NotNull List<Role> roles) {
        List<SimpleGrantedAuthority> list = new ArrayList<>();
        for (Role role : roles) {
            list.add(new SimpleGrantedAuthority("ROLE_"+role.getRoleName().toUpperCase()));
        }
        return list;
    }

    @Override
    public List<Users> findAll() throws Exception {
        return userDao.findAll();
    }

    @Override
    public void save(Users users) throws Exception {
        //对密码进行加密
        users.setPassword(bCryptPasswordEncoder.encode(users.getPassword()));
        userDao.save(users);
    }

    @Override
    public Users findById(String id) throws Exception {
        return userDao.findById(id);
    }

    @Override
    public List<Role> findUserByIdAndAllRole(String userId) throws Exception {
        return userDao.findUserByIdAndAllRole(userId);
    }

    @Override
    public void addRoleToUser(String userId, String[] roleIds) throws Exception {
        for (String roleId : roleIds) {
            userDao.addRoleToUser(userId,roleId);
        }
    }
}
